package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"oauth-test/model"
	"oauth-test/utils"
	"strings"
)

const (
	ClientId     = "66fdbc0569821e34d0ff"
	ClientSecret = "******"
)

func oauth(ctx *gin.Context) {

	code, ok := ctx.GetQuery("code")
	if !ok {
		ctx.String(500, "{code 获取失败}")
		ctx.Abort()
		return
	}

	log.Println("Get code! " + code)

	response, err := utils.SendForAccessToken("https://github.com/login/oauth/access_token?client_id=" + ClientId + "&client_secret=" + ClientSecret + "&code=" + code)
	if err != nil {
		panic(err)
	}
	accessToken := strings.Split(strings.Split(string(response), "=")[1], "&")[0]

	log.Println("Get accessToken! " + accessToken)

	data, err := utils.SendForUserData("https://api.github.com/user", accessToken)
	if err != nil {
		panic(err)
	}

	user := &model.User{}
	err = json.Unmarshal(data, user)
	if err != nil {
		panic(err)
	}

	log.Println("Get data! " + user.Login)

	// 带着 username 跳转到登录成功页面
	ctx.Redirect(http.StatusPermanentRedirect, "http://localhost/usr?username="+user.Login)

}
